package com.czh.myprinter;

import static com.czh.myprinter.APIdata.BASEURL;
import static com.czh.myprinter.APIdata.client_id;
import static com.czh.myprinter.APIdata.client_secret;
import static com.czh.myprinter.APIdata.machine_code;
import static com.czh.myprinter.APIdata.timestamp;
import static com.czh.myprinter.APIdata.uuid;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;


import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.czh.myprinter.HttpRequest;
import com.czh.myprinter.TokenResponse;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private EditText content;
    private TextView tvText;
    private TextView tvimg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        content = findViewById(R.id.content);
        tvText = findViewById(R.id.tvText);
        tvimg = findViewById(R.id.tvimg);

        // 获取token保存
        if (SharedPreferencesExample.getToken(this).isEmpty()) {
            new AccessTokenTask().execute();
        }

        tvText.setOnClickListener(v -> {
//            Log.e("TAG",SharedPreferencesExample.getToken(this));
            if (!content.getText().toString().isEmpty()) {
                new TextPrinterTask().execute(content.getText().toString());
            }
        });

        tvimg.setOnClickListener(v -> {
            // 图片上传
            Log.e("TAG1",SharedPreferencesExample.getToken(this));
        });
    }

    private class AccessTokenTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            try {
                HttpRequest httpRequest = new HttpRequest();
                Map<String, Object> map = new HashMap<>();
                map.put("client_id", client_id);
                map.put("grant_type", "client_credentials");
                map.put("sign", sign());
                map.put("scope", "all");
                map.put("timestamp", timestamp);
                map.put("id", uuid);

                String postResponse = httpRequest.post(APIdata.BASEURL + "/oauth/oauth", map);
//                Gson gson = new Gson();
//                TokenResponse response = gson.fromJson(postResponse, TokenResponse.class);
                JSONObject jsonObject = new JSONObject(postResponse);
                JSONObject  body = jsonObject.getJSONObject("body");
                String accessToken = body.getString("access_token");
                Log.e("TAG",accessToken);
                SharedPreferencesExample.saveToken(MainActivity.this,accessToken );

                return postResponse;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                Log.i("AccessTokenTask", "Access Token: " + result);
            }
        }
    }

    private class TextPrinterTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            String content = strings[0];
            try {
                String token = SharedPreferencesExample.getToken(MainActivity.this);
                HttpRequest httpRequest = new HttpRequest();
                Map<String, Object> map = new HashMap<>();
                map.put("client_id", client_id);
                map.put("sign", sign());
                map.put("timestamp", timestamp);
                map.put("id", uuid);
                map.put("access_token", token);
                map.put("machine_code", machine_code);
                map.put("origin_id", "开始打印");
                map.put("content", content);

                String postResponse = httpRequest.post(APIdata.BASEURL + "/print/index", map);
                return postResponse;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
            }
        }
    }

    public static String sign() {
        String input = client_id + timestamp + client_secret;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes(StandardCharsets.UTF_8));
            BigInteger no = new BigInteger(1, messageDigest);
            StringBuilder hashText = new StringBuilder(no.toString(16));
            while (hashText.length() < 32) {
                hashText.insert(0, "0");
            }
            return hashText.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}